Abstract Class Declaration
An abstract class in Java is declared using the abstract keyword. Here’s the syntax for declaring an abstract class:
Abstract class basic syntax
abstract class ClassName {
// fields and methods
}
Abstract Class Initialization
An abstract class cannot be instantiated, which means you cannot create objects of an abstract class. However, you can create a reference of the abstract class that points to the object of the subclass. Here’s an example:
Abstract Class basic example
Abstract Class basic example in java - Declaration and Initialization
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() {
System.out.println("The dog says: woof woof");
}
}
class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
myDog.sound();
}
}
Output
The dog says: woof woof
In this example, Animal is an abstract class and Dog is a subclass of Animal. We create a reference myDog of type Animal (the abstract class) that points to the object of Dog (the subclass).
Abstract Class : An abstract class can have both abstract methods (methods without a body) and non-abstract methods (methods with a body). It can also have fields (variables). The abstract methods in the abstract class have to be defined by its subclass.
Important points about Abstract Classes
✦ Abstract classes can have constructors and static methods.
✦ They can also have final methods which will force the subclass not to change the body of the method.
✦ If a class has at least one abstract method, then the class must be declared abstract. If a class is declared abstract, it does not need to have any abstract methods.
✦ Abstract classes are a crucial part of the Java Object-Oriented Programming (OOP) concepts, allowing for abstraction and encapsulation.
Remember, the main purpose of an abstract class is to define a common interface for its subclasses. The abstract class defines default behavior and provides default data.